package cs236369.webserver;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import Logging.Monitor;


public class WebServerTest {
	
	Thread serverThread;
	
	@Before
	public void init() throws Exception {
		FileInputStream fip = new FileInputStream("config.xml");
		final WebServer test = new WebServer(fip);
		test.init();
		
		// now the serverThread awaits for connections
		serverThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					System.out.println(InetAddress.getLocalHost().getHostAddress());
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				test.start();
				
			}
		});
	}
	
	@After
	public void tearDown() {
		
	}
	
	private void sendAndReceive(Socket socket) throws IOException {
		
		// send long message to server
		String message = "TestMsg";
		for(int i=0; i<7; ++i){
			message += message;
		}
		
		String req = "GET /../ HTTP/1.1\r\n" +
			 		 "Host: localhost\r\n" +
					 "Content-Length: "+message.length()+"\r\n" +
					 "\r\n"+message;
		byte[] reqBytes = req.getBytes();
		for(int i = 0; i < reqBytes.length; i++)
		{
			socket.getOutputStream().write(reqBytes[i]);
		}
		socket.getOutputStream().flush();
		Monitor.write(this, "Sending the message to the server");
		
		// receiving the message (if exists)
		BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		String str;
		while ((str = rd.readLine()) != null) {
			System.out.println(str);
	    }
	}
	
	private void createClient() {
		Thread client = new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					sendAndReceive(new Socket(InetAddress.getLocalHost(),8082));
				} catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}				
			}
		});
		client.start();
	}
	
	/**
	 * Checking to see if we have 6 threads activated
	 * @throws IOException 
	 * @throws UnknownHostException 
	 * @throws InterruptedException 
	 */
	@Test
	public void testFullQueue() throws 	UnknownHostException, 
										IOException, 
										InterruptedException {
		
		serverThread.start();
		// letting the webserver initialize itself
		Thread.sleep(3000);
		
		// no messages should be in output
		createClient();
		createClient();
		createClient();
		
		// waiting for answers
		Thread.sleep(3000);
	}
	
}
